package com.example.demo.utils;

import cn.hutool.json.JSONObject;
import com.example.demo.exception.BadRequestException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 获取当前登录的用户
 * @author zjj
 * @date 2021-05-13
 */
public class SecurityUtils {

    public static UserDetails getUserDetails(){
        UserDetails userDetails;
        try {
            Object obj=SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        将obj对象强制转换为UserDetails类
            userDetails = (UserDetails) obj;
        }catch (Exception e){
            throw new BadRequestException(HttpStatus.UNAUTHORIZED,"登录状态过期");
        }
        return userDetails;
    }

    /**
     * 获取系统登录用户名
     * @return
     */
    public static String getUsername(){
        Object obj = getUserDetails();
        return new JSONObject(obj).get("username",String.class);
    }
}
